<template>
  <div class="backstage-content">
    <el-card>
      <!-- // 头部input -->
      <div class="input">
        <el-button type="success" icon="el-icon-edit" size="small" @click="openAdd">添加菜单</el-button>
      </div>

      <!-- 树形表格 -->
      <el-table
        :data="treeList"
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        default-expand-all
        :tree-props="{children: 'Childs', hasChildren:true}"
      >
        <el-table-column
          prop="title"
          label="标题"
          width="400px"
        />
        <el-table-column
          prop="code"
          label="编号"
        />
        <el-table-column
          label="操作"
          fixed="right"
          width="400px"
          align="center"
        >
          <template slot-scope="scope">
            <div class="button">
              <el-button type="primary" plain icon="el-icon-edit" circle @click="set(scope.row)" />
              <el-button type="danger" plain icon="el-icon-delete" circle @click="remove(scope.row)" />
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加菜单 -->
      <add
        :is-show.sync="isShow"
        title="添加权限组名单"
        :tree-list="treeList"
        @getmenuTree="getmenuTree"
      />
      <!-- 修改菜单 -->
      <add
        :is-show.sync="isShow2"
        :is-set="true"
        title="修改权限组名单"
        :tree-list="treeList"
        :form-data="formData"
        @getmenuTree="getmenuTree"
      />
      <!-- 权限组传值 -->
    </el-card>
  </div>
</template>

<script>
import { menusListAPI, delMenusListAPI, menusDetailAPI } from '@/api/menus'
import { pointsToChilds } from '@/utils/utils'
import add from '../components/add-menus.vue'

export default {
  components: {
    add
  },
  data() {
    return {
      treeList: [], // 树形列表
      formData: {}, // 回显数据
      isShow: false, // 开启添加弹窗
      isShow2: false // 开启修改弹窗
    }
  },
  created() {
    this.getmenuTree()
  },
  methods: {
    // 获取菜单列表
    async getmenuTree() {
      const res = await menusListAPI()
      this.treeList = pointsToChilds(res)
    },
    // 开启修改弹窗做回显
    async set(row) {
      try {
        this.isShow2 = true
        this.formData = await menusDetailAPI(row.id)
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 开启弹窗
    openAdd() {
      this.isShow = true
    },
    // 删除菜单
    async remove(row) {
      try {
        await delMenusListAPI(row.id)
        this.getmenuTree()
        this.$message.success('删除成功')
      } catch (error) {
        this.$message.error(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.backstage-content {
  padding-right: 10px;
}

.input {
  width: 100%;
  display: flex;
  justify-content: right;
}

.el-table{
  margin-top: 20px;
}
</style>
